<template>
  <div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="合同状态" prop="carStatus">
        <el-select v-model="queryParams.status" placeholder="请选择合同状态" class="custom-select">
          <el-option
            v-for="dict in dict.type.status"
            :key="dict.value"
            :label="dict.label"
            :value="parseInt(dict.value)"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:contracts:add']"
          class="custom-button"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:contracts:edit']"
          class="custom-button"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:contracts:remove']"
          class="custom-button"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:contracts:export']"
          class="custom-button"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      :data="contractsList"
      style="width: 100%"
      class="enhanced-table"
      :header-cell-style="headerStyle"
      :row-class-name="tableRowClassName"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="合同ID" align="center" prop="id" />
      <el-table-column label="合同编号" align="center" prop="contractNumber" />
      <el-table-column label="房源地址" align="center" prop="propertyAddress" />
      <el-table-column label="签约日期" align="center" prop="signingDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租期开始日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="租期结束日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合同状态" align="center">
        <template slot-scope="scope">
          <el-tag
            :type="statusType(scope.row.status)"
            class="status-tag"
          >
            {{ scope.row.status | statusFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="租金金额" align="center" prop="rentAmount" />
      <el-table-column label="支付周期" align="center" prop="paymentCycle" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_cycle" :value="scope.row.paymentCycle" />
        </template>
      </el-table-column>
      <el-table-column label="押金金额" align="center" prop="depositAmount" />
      <el-table-column label="租金递增条款" align="center" prop="rentIncreaseTerms" />
      <el-table-column label="房东ID" align="center" prop="landlordId" />
      <el-table-column label="租客ID" align="center" prop="tenantId" />
      <el-table-column label="附加条款" align="center" prop="additionalTerms" />
      <el-table-column label="电子签名" align="center" prop="electronicSignature" />
      <el-table-column label="签署时间" align="center" prop="signatureTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signatureTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解约日期" align="center" prop="terminationDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.terminationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="解约原因" align="center" prop="terminationReason" />
      <el-table-column label="解约条款" align="center" prop="terminationTerms" />
      <el-table-column label="解约协议" align="center" prop="terminationAgreement" />
      <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template slot-scope="scope">
          <div class="operation-buttons">
            <el-button
              size="mini"
              class="operation-button"
              @click="handleDetail(scope.row.id)"
              style="color: #409EFF;"
            >
              <i class="el-icon-document"></i>详情
            </el-button>
            <el-button
              size="mini"
              class="operation-button"
              @click="handleUpdate(scope.row)"
              style="color: #67C23A;"
            >
              <i class="el-icon-edit"></i>修改
            </el-button>
            <el-button
              size="mini"
              class="operation-button"
              @click="handleDelete(scope.row)"
              style="color: #F56C6C;"
            >
              <i class="el-icon-delete"></i>删除
            </el-button>
            <el-button
              v-if="scope.row.status != 4"
              size="mini"
              class="operation-button"
              @click="handleTermination(scope.row)"
              style="color: #E6A23C;"
            >
              <i class="el-icon-warning"></i>解约
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合同信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="680px"
      class="enhanced-dialog"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="enhanced-form"
      >
        <!-- 基本信息区块 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <div class="form-columns">
            <div class="form-col">
              <el-form-item label="合同编号" prop="contractNumber">
                <el-input
                  v-model="form.contractNumber"
                  placeholder="请输入合同编号"
                  clearable
                  class="enhanced-input"
                />
              </el-form-item>
              <el-form-item label="房源地址" prop="propertyAddress">
                <el-input
                  v-model="form.propertyAddress"
                  placeholder="请输入房源地址"
                  clearable
                  class="enhanced-input"
                />
              </el-form-item>
              <el-form-item label="签约日期" prop="signingDate">
                <el-date-picker
                  v-model="form.signingDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择签约日期"
                  class="full-width-picker"
                />
              </el-form-item>
            </div>
            <div class="form-col">
              <el-form-item label="租期开始" prop="startDate">
                <el-date-picker
                  v-model="form.startDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择开始日期"
                  class="full-width-picker"
                />
              </el-form-item>
              <el-form-item label="租期结束" prop="endDate">
                <el-date-picker
                  v-model="form.endDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择结束日期"
                  class="full-width-picker"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 租金相关区块 -->
        <div class="form-section">
          <div class="section-title">租金条款</div>
          <div class="form-columns">
            <div class="form-col">
              <el-form-item label="租金金额" prop="rentAmount">
                <el-input
                  v-model="form.rentAmount"
                  placeholder="请输入金额"
                  class="enhanced-input"
                >
                  <template slot="append">元/月</template>
                </el-input>
              </el-form-item>
              <el-form-item label="支付周期" prop="paymentCycle">
                <el-select
                  v-model="form.paymentCycle"
                  placeholder="选择支付周期"
                  class="full-width-select"
                >
                  <el-option
                    v-for="dict in dict.type.payment_cycle"
                    :key="dict.value"
                    :label="dict.label"
                    :value="parseInt(dict.value)"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="form-col">
              <el-form-item label="押金金额" prop="depositAmount">
                <el-input
                  v-model="form.depositAmount"
                  placeholder="请输入金额"
                  class="enhanced-input"
                >
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="租金递增" prop="rentIncreaseTerms">
                <el-input
                  v-model="form.rentIncreaseTerms"
                  placeholder="例：每年递增5%"
                  class="enhanced-input"
                />
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 关联信息区块 -->
        <div class="form-section">
          <div class="section-title">关联信息</div>
          <div class="form-columns">
            <div class="form-col">
              <el-form-item label="房东ID" prop="landlordId">
                <el-input
                  v-model="form.landlordId"
                  placeholder="输入房东ID"
                  class="enhanced-input"
                />
              </el-form-item>
            </div>
            <div class="form-col">
              <el-form-item label="租户选择" prop="tenantId">
                <el-select
                  v-model="form.tenantId"
                  placeholder="选择租客"
                  filterable
                  class="full-width-select"
                >
                  <el-option
                    v-for="user in users"
                    :key="user.userId"
                    :label="user.userName"
                    :value="user.userId"
                  />
                </el-select>
              </el-form-item>
            </div>
          </div>
        </div>

        <!-- 高级条款区块 -->
        <div class="form-section">
          <div class="section-title">附加条款</div>
          <el-form-item label="电子签名" prop="electronicSignature">
            <el-input
              v-model="form.electronicSignature"
              type="textarea"
              :rows="2"
              placeholder="输入签名存储路径或Base64编码"
              class="enhanced-textarea"
            />
          </el-form-item>
          <el-form-item label="附加条款" prop="additionalTerms">
            <el-input
              v-model="form.additionalTerms"
              type="textarea"
              :rows="3"
              placeholder="输入特殊约定条款"
              class="enhanced-textarea"
            />
          </el-form-item>
        </div>

<!--        &lt;!&ndash; 解约信息区块 &ndash;&gt;-->
<!--        <div class="form-section termination-section">-->
<!--          <div class="section-title">解约条款</div>-->
<!--          <div class="form-columns">-->
<!--            <div class="form-col">-->
<!--              <el-form-item label="解约日期" prop="terminationDate">-->
<!--                <el-date-picker-->
<!--                  v-model="form.terminationDate"-->
<!--                  type="date"-->
<!--                  value-format="yyyy-MM-dd"-->
<!--                  placeholder="选择解约日期"-->
<!--                  class="full-width-picker"-->
<!--                />-->
<!--              </el-form-item>-->
<!--              <el-form-item label="解约原因" prop="terminationReason">-->
<!--                <el-input-->
<!--                  v-model="form.terminationReason"-->
<!--                  placeholder="输入解约原因"-->
<!--                  class="enhanced-input"-->
<!--                />-->
<!--              </el-form-item>-->
<!--            </div>-->
<!--            <div class="form-col">-->
<!--              <el-form-item label="解约条款" prop="terminationTerms">-->
<!--                <el-input-->
<!--                  v-model="form.terminationTerms"-->
<!--                  type="textarea"-->
<!--                  :rows="2"-->
<!--                  placeholder="输入解约条款"-->
<!--                  class="enhanced-textarea"-->
<!--                />-->
<!--              </el-form-item>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
      </el-form>

      <div slot="footer" class="enhanced-footer">
        <el-button @click="cancel" class="dialog-btn cancel-btn">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm"
          class="dialog-btn submit-btn"
        >确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="terminationTitle"
      :visible.sync="terminationOpen"
      width="580px"
      class="modern-dialog"
      custom-class="shadow-dialog"
      append-to-body>
      <el-form
        ref="terminationForm"
        :model="terminationForm"
        :rules="terminationRules"
        label-width="100px"
        class="elegant-form">
        <!-- 解约日期 -->
        <el-form-item label="📅 解约日期" prop="terminationDate">
          <el-date-picker
            v-model="terminationForm.terminationDate"
            type="date"
            value-format="yyyy-MM-dd"
            popper-class="modern-datepicker"
            placeholder="选择解约日期"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() < Date.now() - 8.64e7;
              }
            }">
            <i slot="suffix" class="el-icon-date"></i>
          </el-date-picker>
        </el-form-item>
        <!-- 解约原因 -->
        <el-form-item label="📝 解约原因" prop="terminationReason">
          <el-input
            v-model="terminationForm.terminationReason"
            placeholder="请输入详细原因..."
            suffix-icon="el-icon-edit"
            class="gradient-input">
          </el-input>
        </el-form-item>
        <!-- 解约条款 -->
        <el-form-item label="📜 解约条款" prop="terminationTerms">
          <el-input
            v-model="terminationForm.terminationTerms"
            type="textarea"
            :rows="3"
            placeholder="请输入条款内容..."
            class="scroll-textarea">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitTerminationForm"
          class="neon-button confirm-btn">
          ✓ 确认提交
        </el-button>
        <el-button
          @click="cancelTermination"
          class="glass-button cancel-btn">
          ✕ 取消操作
        </el-button>
        <!-- 新增查看按钮 -->
        <el-button
          type="info"
          plain
          @click="handleViewTermination"
          class="custom-button">
          <i class="el-icon-document"></i>查看解约合约
        </el-button>
      </div>
    </el-dialog>

    <!-- 新增查看解约合约对话框 -->
    <el-dialog
      title="解约合约详情"
      :visible.sync="viewDialogVisible"
      width="600px"
      class="detail-dialog">
      <div class="termination-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="解约条款">
            <el-input
              type="textarea"
              :rows="6"
              :value="defaultTerminationTerms"
              readonly
              class="enhanced-textarea"/>
          </el-descriptions-item>
          <el-descriptions-item label="电子签名">

            <el-input
              v-model="form.electronicSignature"
              type="text"
              placeholder="请输入签名文字（如：张三电子签）"
              clearable
              class="enhanced-input"
            >
              <template slot="append">
                <el-tooltip content="支持中文/英文签名">
                  <i class="el-icon-info"></i>
                </el-tooltip>
              </template>
            </el-input>

          </el-descriptions-item>
        </el-descriptions>
      </div>
      <span slot="footer" class="dialog-footer">
    <el-button @click="viewDialogVisible = false">关闭</el-button>
  </span>
      <el-descriptions-item label="调试信息">
        {{ defaultTerminationTerms.substring(0,30) + "..." }}
      </el-descriptions-item>
    </el-dialog>

    <!-- 合同详情对话框 -->
    <el-dialog title="合同详情" :visible.sync="dialogVisible" width="800px" class="custom-detail-dialog">
      <div class="detail-container">
        <!-- 合同基本信息 -->
        <div class="section">
          <div class="section-title">合同基本信息</div>
          <el-descriptions :column="2" border class="custom-descriptions">
            <el-descriptions-item label="合同ID">{{ contractDetail[0] && contractDetail[0].id }}</el-descriptions-item>
            <el-descriptions-item label="房东ID">{{ contractDetail[0] && contractDetail[0].landlordId }}</el-descriptions-item>
            <el-descriptions-item label="租客ID">{{ contractDetail[0] && contractDetail[0].tenantId }}</el-descriptions-item>
            <el-table-column label="租金金额" align="center">
              <template slot-scope="scope">
                <span class="money-cell">{{ scope.row.rentAmount }} 元</span>
              </template>
            </el-table-column>
            <el-descriptions-item label="支付周期">
              <dict-tag v-if="contractDetail[0]" :options="dict.type.payment_cycle" :value="contractDetail[0].paymentCycle"/>
            </el-descriptions-item>
            <el-descriptions-item label="押金金额">{{ contractDetail[0] && contractDetail[0].depositAmount }} 元</el-descriptions-item>
            <el-descriptions-item label="电子签名时间" :span="2">
              {{ contractDetail[0] && parseTime(contractDetail[0].signatureTime) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 双方信息 -->
        <div class="section">
          <div class="section-title">签约方信息</div>
          <div class="user-info-card">
            <div class="user-info-item">
              <span class="info-label">昵称：</span>
              <span class="info-value">{{ contractDetail[0] ? contractDetail[0].nickName : '无' }}</span>
            </div>
            <div class="user-info-item">
              <span class="info-label">账户：</span>
              <span class="info-value">{{ contractDetail[0] ? contractDetail[0].userName : '无' }}</span>
            </div>
            <div class="user-info-item">
              <span class="info-label">手机号：</span>
              <span class="info-value">{{ contractDetail[0] ? contractDetail[0].phonenumber : '无' }}</span>
            </div>
            <div class="user-info-item">
              <span class="info-label">性别：</span>
              <span class="info-value">{{ contractDetail[0] ? genderDisplay(contractDetail[0].sex) : '未知' }}</span>
            </div>
          </div>
        </div>

        <!-- 解约信息 -->
        <div v-if="contractDetail[0] && contractDetail[0].terminationDate" class="section">
          <div class="section-title warning-title">解约信息</div>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="解约日期">{{ contractDetail[0].terminationDate }}</el-descriptions-item>
            <el-descriptions-item label="解约原因">{{ contractDetail[0].terminationReason }}</el-descriptions-item>
            <el-descriptions-item label="解约条款">{{ contractDetail[0].terminationTerms }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false" class="custom-close-btn">关 闭</el-button>
  </span>
    </el-dialog>
  </div>

</template>

<script>
import { listContracts, getContracts, delContracts, addContracts, updateContracts } from "@/api/business/contracts";
import { getUser } from "@/api/business/contracts"; // 引入 getUser 方法
import { getContractsDetail } from '@/api/business/contracts'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        1: '已签约',
        2: '进行中',
        3: '即将到期',
        4: '已解约'
      }
      return statusMap[status] || '未知'
    }
  },
  dicts: ["status","payment_cycle"],
  name: "Contracts",
  data() {
    return {
      defaultTerminationTerms: `
      解约协议

      甲方（出租方）：宏烨找房有限公司
      乙方（承租方）：${this.$store.state.user.name}

      第一条 解约条款
      本解约协议及其补充条款均为原《电子服务合同》不可分割的一部分，与原合同具有同等法律效力。

      第二条 解约程序
      甲乙双方确认已清楚解约后的权利义务关系，同意按以下流程办理：
      1. 乙方通过电子签约系统提交解约申请
      2. 甲方在3个工作日内进行电子签章确认
      3. 系统自动生成《解约确认书》

      第三条 电子签约
      双方确认本协议采用电子签名方式签署：
      - 甲方签章：宏烨找房有限公司电子公章（序列号：HYZF-EC-2023）
      - 乙方签名：${this.$store.state.user.name}（用户ID：${this.$store.state.user.username}）
      电子签名与手写签名具有同等法律效力

      第四条 争议解决
      发生争议时，双方同意优先通过平台协商解决。协商不成时，提交上海仲裁委员会仲裁。

      第五条 协议生效
      本协议自双方完成电子签名之日起生效，协议文本由系统自动存档（哈希值：${Date.now()}）
    `,
      viewDialogVisible: false,
      viewTerminationData: {
        terminationTerms: null,
        electronicSignature: null
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同信息表格数据
      contractsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractNumber: null,
        propertyAddress: null,
        signingDate: null,
        startDate: null,
        endDate: null,
        status: null,
        rentAmount: null,
        paymentCycle: null,
        depositAmount: null,
        rentIncreaseTerms: null,
        landlordId: null,
        tenantId: null,
        additionalTerms: null,
        electronicSignature: null,
        signatureTime: null,
        terminationDate: null,
        terminationReason: null,
        terminationTerms: null,
        terminationAgreement: null,
        createdAt: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        contractNumber: [
          { required: true, message: "合同编号不能为空", trigger: "blur" }
        ],
        propertyAddress: [
          { required: true, message: "房源地址不能为空", trigger: "blur" }
        ],
        signingDate: [
          { required: true, message: "签约日期不能为空", trigger: "blur" }
        ],
        startDate: [
          { required: true, message: "租期开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "租期结束日期不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "合同状态不能为空", trigger: "change" }
        ],
        rentAmount: [
          { required: true, message: "租金金额不能为空", trigger: "blur" }
        ],
        paymentCycle: [
          { required: true, message: "支付周期不能为空", trigger: "blur" }
        ],
        depositAmount: [
          { required: true, message: "押金金额不能为空", trigger: "blur" }
        ],
        landlordId: [
          { required: true, message: "房东ID不能为空", trigger: "blur" }
        ],
        tenantId: [
          { required: true, message: "租客ID不能为空", trigger: "blur" }
        ],
        signatureTime: [
          { required: true, message: "签署时间不能为空", trigger: "blur" }
        ],
      },
      users: [], // 新增用户数据数组
      terminationTitle: "",
      terminationOpen: false,
      terminationForm: {
        terminationDate: new Date().toISOString().split('T')[0], // 设置默认值为当前系统时间
        terminationReason: null,
        terminationTerms: null,
        terminationAgreement: null,
        electronicSignature: null // 新增电子签名字段
      },
      terminationRules: {
        terminationDate: [
          { required: true, message: "解约日期不能为空", trigger: "change" }
        ],
        terminationReason: [
          { required: true, message: "解约原因不能为空", trigger: "blur" }
        ],
        terminationTerms: [
          { required: true, message: "解约条款不能为空", trigger: "blur" }
        ],
        terminationAgreement: [
          { required: true, message: "解约协议不能为空", trigger: "blur" }
        ],
        electronicSignature: [
          { required: true, message: "电子签名不能为空", trigger: "blur" } // 新增电子签名校验规则
        ]
      },
      dialogVisible: false,
      contractDetail: []
    };
  },
  created() {
    this.getList();
    this.getUsers(); // 页面加载时获取用户数据
  },
  computed: {
    dynamicTerminationTerms() {
      return `
      解约协议
      甲方：${this.$store.state.user.name}
      用户ID：${this.$store.state.user.username}
      ${/* 其他动态内容 */''}
    `
    },
    genderDisplay() {
      return function(sex) {
        switch (sex) {
          case 0:
            return '男';
          case 1:
            return '女';
          case 2:
            return '未知';
          default:
            return '未知';
        }
      };
    }, statusType() {
      return function(status) {
        const typeMap = {
          0: 'info',
          1: 'success',
          2: '',
          3: 'warning',
          4: 'danger'
        }
        return typeMap[status]
      }
    }
  },
  methods: {
    // 查看解约合约
    handleViewTermination() {
      this.viewTerminationData = {
        terminationTerms: this.defaultTerminationTerms, // 传递默认条款
        electronicSignature: this.terminationForm.electronicSignature
      }
      this.viewDialogVisible = true;
    },

    // 判断签名是否为图片
    isImageSignature(signature) {
      return signature?.startsWith('data:image/') ||
        signature?.match(/\.(jpg|jpeg|png|gif)$/i);
    },
    // 表头样式
    headerStyle() {
      return {
        backgroundColor: '#f8f9fa',
        color: '#303133',
        fontSize: '14px'
      }
    },
    // 行样式
    tableRowClassName({ rowIndex }) {
      return rowIndex % 2 === 0 ? 'even-row' : 'odd-row'
    },
    /** 查询合同信息列表 */
    getList() {
      this.loading = true;
      listContracts(this.queryParams).then(response => {
        this.contractsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        contractNumber: null,
        propertyAddress: null,
        signingDate: null,
        startDate: null,
        endDate: null,
        status: null,
        rentAmount: null,
        paymentCycle: null,
        depositAmount: null,
        rentIncreaseTerms: null,
        landlordId: null,
        tenantId: null,
        additionalTerms: null,
        electronicSignature: null,
        signatureTime: null,
        terminationDate: null,
        terminationReason: null,
        terminationTerms: null,
        terminationAgreement: null,
        createdAt: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams=null;
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加合同信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContracts(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改合同信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateContracts(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContracts(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合同信息编号为"' + ids + '"的数据项？').then(function() {
        return delContracts(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 发起解约按钮操作 */
    handleTermination(row) {
      this.resetTerminationForm();
      this.terminationForm = {
        ...row,
        status: 4,
        terminationDate: new Date().toISOString().split('T')[0] // 设置默认值为当前系统时间
      }; // 设置状态为 4
      this.terminationOpen = true;
      this.terminationTitle = "发起解约";
    },
    /** 取消解约按钮操作 */
    cancelTermination() {
      this.terminationOpen = false;
      this.resetTerminationForm();
    },
    /** 重置解约表单 */
    resetTerminationForm() {
      this.terminationForm = {
        terminationReason: null,
        terminationTerms: null,
        terminationAgreement: null
      };
      this.resetForm("terminationForm");
    },
    /** 提交解约表单 */
    submitTerminationForm() {
      this.$refs["terminationForm"].validate(valid => {
        if (valid) {
          updateContracts(this.terminationForm).then(response => {
            this.$modal.msgSuccess("解约成功");
            this.terminationOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/contracts/export', {
        ...this.queryParams
      }, `contracts_${new Date().getTime()}.xlsx`)
    },

    // 新增获取用户数据的方法
    getUsers() {
      getUser().then(response => {
        this.users = response.data;
      });
    },
    handleDetail(id) {
      getContractsDetail(id).then(response => {
        debugger
        const contractData = response.data;
        this.contractDetail = [contractData];
        this.dialogVisible = true;
      });
    }
  }
};
</script>

<style scoped>
.enhanced-textarea.readonly >>> .el-textarea__inner {
  background-color: #f5f7fa;
  color: #606266;
  cursor: not-allowed;
}
.enhanced-textarea {
  font-family: "Microsoft YaHei", sans-serif;
  line-height: 1.8;
  border: 1px solid #e4e7ed;
  padding: 12px;
  white-space: pre-wrap;
}
.custom-select {
  width: 200px;
}

.custom-button {
  margin-bottom: 10px;
}

.custom-text-button {
  color: #409EFF;
  text-decoration: underline;
}

.custom-table {
  margin-top: 20px;
}

.custom-dialog {
  border-radius: 8px;
}

.custom-form {
  padding: 20px;
}

/* 详情对话框美化 */
.custom-detail-dialog {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.detail-container {
  padding: 16px;
}

.section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 4px solid #409EFF;
}

.warning-title {
  border-left-color: #F56C6C;
}

.user-info-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.user-info-item {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-label {
  color: #606266;
  min-width: 60px;
}

.info-value {
  color: #303133;
  font-weight: 500;
}

/* 全局表格美化 */
.el-table {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.el-table th {
  background-color: #f8f9fa !important;
  color: #303133;
}

.el-table--striped .el-table__body tr.el-table__row--striped td {
  background: #fafafa;
}

/* 按钮统一风格 */
.custom-close-btn {
  padding: 10px 24px;
  border-radius: 6px;
}

/* 表单输入框 */
.el-input__inner {
  border-radius: 6px !important;
}

/* 对话框标题 */
.el-dialog__title {
  font-weight: 600 !important;
  color: #303133 !important;
}

/* 对话框整体样式 */
.enhanced-dialog {
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

/* 表单区块样式 */
.form-section {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  border: 1px solid #eaeef5;
}

.termination-section {
  background: #fff5f5;
  border-color: #ffe0e0;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #409EFF;
}

.termination-section .section-title {
  border-color: #f56c6c;
}

/* 分栏布局 */
.form-columns {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
}

.form-col {
  min-width: 0;
}

/* 输入组件样式 */
.enhanced-input .el-input__inner {
  border-radius: 6px;
  transition: all 0.3s;
}

.full-width-picker,
.full-width-select {
  width: 100%;
}

.enhanced-textarea .el-textarea__inner {
  border-radius: 8px;
  min-height: 80px;
  padding: 12px;
  line-height: 1.5;
}

/* 按钮样式 */
.enhanced-footer {
  padding-top: 20px;
  text-align: right;
}

.dialog-btn {
  padding: 10px 24px;
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.2s;
}

.submit-btn {
  background: #409EFF;
  border-color: #409EFF;
}

.submit-btn:hover {
  opacity: 0.9;
  transform: translateY(-1px);
}

.cancel-btn {
  margin-right: 12px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .form-columns {
    grid-template-columns: 1fr;
  }

  .enhanced-dialog {
    width: 90% !important;
  }
}

/* 高级表格样式 */
.enhanced-table {
  border: 1px solid #ebeef5;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.06);
}

/* 表头样式 */
.enhanced-table th {
  background: #f8fafc !important;
  font-weight: 600;
  color: #2c3e50;
  height: 56px;
}

/* 表格行样式 */
.enhanced-table td {
  height: 52px;
  transition: all 0.3s;
}

/* 斑马纹效果 */
.enhanced-table .el-table__row--striped td {
  background: #fafbfc;
}

/* 悬停效果 */
.enhanced-table .el-table__row:hover td {
  background-color: #f5f7fa !important;
}

/* 操作栏优化 */
.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.operation-button {
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.2s;
}

.operation-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0,0,0,0.08);
}

/* 状态标签美化 */
.status-tag {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
}

/* 金额突出显示 */
.money-cell {
  font-weight: 600;
  color: #409EFF;
}

/* 分页组件美化 */
.pagination-container {
  margin-top: 24px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

/* 对话框整体样式 */
.modern-dialog {
  border-radius: 12px;
  background: linear-gradient(145deg, #f8f9fa 0%, #ffffff 100%);
}

.shadow-dialog {
  box-shadow: 0 10px 30px rgba(0,0,0,0.15) !important;
}

/* 表单样式 */
.elegant-form {
  padding: 20px 30px;
}

.elegant-form >>> .el-form-item__label {
  color: #2c3e50;
  font-weight: 600;
  letter-spacing: 0.5px;
}

/* 输入框增强 */
.gradient-input >>> .el-input__inner {
  border-radius: 8px;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
  background: linear-gradient(90deg, #f8f9fa 0%, #ffffff 50%);
}

.gradient-input >>> .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 8px rgba(64,158,255,0.2);
}

/* 特殊文本域 */
.scroll-textarea >>> .el-textarea__inner {
  border-radius: 8px;
  resize: vertical;
  background: #f8f9fa;
  border: 1px solid #e0e0e0;
  padding: 12px;
}

/* 现代按钮 */
.neon-button {
  border: none;
  border-radius: 8px;
  padding: 12px 28px;
  background: linear-gradient(135deg, #409eff, #66b1ff);
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(64,158,255,0.3);
}

.glass-button {
  background: rgba(255,255,255,0.9);
  border: 1px solid rgba(0,0,0,0.1);
  backdrop-filter: blur(4px);
  color: #606266;
  border-radius: 8px;
  padding: 12px 28px;
  transition: all 0.3s ease;
}

/* 悬停效果 */
.neon-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 20px rgba(64,158,255,0.4);
}

.glass-button:hover {
  background: rgba(245,245,245,0.9);
  color: #409eff;
}

/* 日期选择器美化 */
.modern-datepicker {
  border-radius: 8px !important;
  box-shadow: 0 8px 20px rgba(0,0,0,0.12) !important;
}

/* 全局主题色 */
:root {

  --contract-red: #E74C3C;  /* 新增合约警示色 */
  --legal-text: #2C3E50;    /* 法律文书专用色 */
  --primary-color: #409EFF;
  --success-color: #67C23A;
  --warning-color: #E6A23C;
  --danger-color: #F56C6C;
  --info-color: #909399;
  --bg-gradient: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
}

/* 统一过渡效果 */
* {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 增强型表格 */
.enhanced-table {
  border: 1px solid #ebeef5;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.06);

  >>> .el-table__header th {
    background: var(--bg-gradient) !important;
    font-weight: 600;
    color: #2c3e50;
    height: 56px;
    border-bottom: 2px solid var(--primary-color);
  }

  >>> .el-table__body td {
    padding: 12px 0;
  }

  >>> .el-table__row--striped td {
    background: #fafbfc;
  }

  >>> .el-table__row:hover td {
    background: #f5f7fa !important;
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  }
}

/* 现代按钮组 */
.action-buttons {
  .el-button {
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    letter-spacing: 0.5px;

    &--primary {
      background: linear-gradient(135deg, var(--primary-color), #66b1ff);
      border: none;
      box-shadow: 0 4px 15px rgba(64,158,255,0.3);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(64,158,255,0.4);
      }
    }

    &--text {
      color: var(--primary-color);
      padding: 8px;
      border-radius: 6px;

      &:hover {
        background: rgba(64,158,255,0.1);
      }
    }
  }
}

/* 高级表单样式 */
.enhanced-form {
  padding: 24px;
  background: var(--bg-gradient);
  border-radius: 12px;

  .form-section {
    margin-bottom: 28px;
    padding: 20px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: var(--primary-color);
      padding-bottom: 12px;
      border-bottom: 2px solid rgba(64,158,255,0.2);
      margin-bottom: 20px;
    }
  }

  .el-input__inner {
    border-radius: 8px;
    padding: 12px 16px;
    background: #f8f9fa;

    &:focus {
      box-shadow: 0 0 0 2px rgba(64,158,255,0.2);
    }
  }
}

/* 3D卡片式对话框 */
.modern-dialog {
  border-radius: 16px !important;
  background: var(--bg-gradient);
  box-shadow: 0 12px 32px rgba(0,0,0,0.12) !important;

  .el-dialog__header {
    border-bottom: 1px solid #eaeef5;
    padding: 20px 24px;

    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
    }
  }

  .el-dialog__body {
    padding: 24px 32px;
  }
}

/* 状态标签 */
.status-tag {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  letter-spacing: 0.5px;

  &.el-tag--success {
    background: rgba(103,194,58,0.1);
    border-color: rgba(103,194,58,0.2);
  }

  &.el-tag--danger {
    background: rgba(245,108,108,0.1);
    border-color: rgba(245,108,108,0.2);
  }
}

/* 分页组件美化 */
.pagination-container {
  margin-top: 24px;
  padding: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.06);
}

/* 响应式优化 */
@media (max-width: 768px) {
  .form-columns {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .enhanced-table {
    >>> th, >>> td {
      padding: 8px !important;
    }

    >>> .operation-buttons {
      flex-direction: column;
      gap: 4px;
    }
  }

  .modern-dialog {
    width: 90% !important;
  }
}

/* 微交互动画 */
@keyframes float {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-4px); }
}

.float-animation {
  animation: float 3s ease-in-out infinite;
}

/* 细节增强 */
.el-icon {
  vertical-align: -0.15em;
}

.operation-button {
  i {
    margin-right: 4px;
  }

  &:hover {
    transform: scale(1.05);
    filter: brightness(1.1);
  }
}

/* 高级滚动条 */
*::-webkit-scrollbar {
  width: 8px;
  height: 8px;
  background-color: rgba(0,0,0,0.05);
}

*::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: rgba(144,147,153,0.3);

  &:hover {
    background-color: rgba(144,147,153,0.5);
  }
}

/* 新增样式 */
.detail-dialog {
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.termination-detail {
  padding: 20px;
}

.terms-content {
  white-space: pre-wrap;
  line-height: 1.6;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

.signature-preview {
  min-height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
}

.signature-image {
  max-width: 100%;
  max-height: 200px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 5px;
}

.no-signature {
  color: #909399;
  font-style: italic;
}

/* 按钮间距调整 */
.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
.terms-content::before {
  content: "宏烨找房有限公司 - 机密文件";
  display: block;
  color: #95A5A6;
  font-size: 12px;
  border-bottom: 1px solid #EDF2F7;
  margin-bottom: 15px;
  padding-bottom: 8px;
}
.signature-preview {
  position: relative;

  &::after {
    content: attr(data-user-id);
    position: absolute;
    color: rgba(64,158,255,0.1);
    font-size: 48px;
    transform: rotate(-30deg);
    pointer-events: none;
  }
}

/* 新增按钮动效 */
.neon-button {
  position: relative;
  overflow: hidden;

  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 300%;
    height: 300%;
    background: rgba(255,255,255,0.2);
    transform: translate(-50%, -50%) rotate(45deg);
    transition: all 0.6s ease;
  }

  &:hover::after {
    width: 0;
    height: 0;
  }
}

/* 表格行点击效果 */
.enhanced-table >>> .el-table__row {
  cursor: pointer;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &:hover {
    transform: translateX(8px);
    box-shadow: 4px 0 12px rgba(64,158,255,0.1);
  }
}
</style>

